package com.example.notes;

import interfaces.Noteable;

import java.text.DateFormat;
import java.util.Date;

import notes.NoteWithPicture;
import notes.NotesDatabase;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class EditNoteActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.activity_edit_note);
		
		
		final int position = getIntent().getIntExtra("CheckedIndex", 0);
		
		final Noteable note = NotesDatabase.getNote(position);
		
		final TextView title = (TextView) findViewById(R.id.editTitle);
		final TextView text = (TextView) findViewById(R.id.editText);
		title.setText(note.getTitle());
		text.setText(note.getText());
		
		Button saveButton = (Button) findViewById(R.id.saveButton);
		saveButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String currentDateTimeString = DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());
				if(title.getText().toString().length() >= 1) {
					if(note instanceof NoteWithPicture)
						NotesDatabase.editNote(title.getText().toString(), text
								.getText().toString(), currentDateTimeString, ((NoteWithPicture) note).getPicturePath(),
								position);
					else 
						NotesDatabase.editNote(title.getText().toString(), text
								.getText().toString(), currentDateTimeString, null,
								position);
					showToast("Note edited!");
					finish();
				}
				else {
					showToast("Note could not be edited!\nPlease add a Title!");
				}
				
			}
		});
		
		
		}
	
	@Override
	protected void onDestroy() {
		finish();
		super.onDestroy();
	}
	
	private void showToast(String text) {
		Toast toast = Toast.makeText(EditNoteActivity.this, text, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
}
